import axios, { AxiosRequestConfig } from 'axios';
import qs from 'qs';

export const baseURL = 'http://127.0.0.1:7001';

const axiosInstance = axios.create({
  baseURL,
  timeout: 10000, //设置超时时间和跨域是否允许携带凭证
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'token': localStorage.getItem('token') || '',
  },
  transformRequest: data => qs.stringify(data),
  validateStatus: status => /^(2|3)\d{2}$/.test(String(status)),
});

/**
 * 设置请求拦截器
 * token验证
 */
axiosInstance.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (config.headers) {
    config.headers.token = token || "";
  }
  return config;
}, error => {
  return Promise.reject(error);
});

export interface AxiosResponse<T = {code : string}> {
  data: T;
  status: number;
  statusText: string;
  headers: any;
  config: AxiosRequestConfig;
  request?: any;
}

/**
 * 响应拦截器
 */
axiosInstance.interceptors.response.use(response => {
  switch (Number(response.data.code)) {
    case 401: // 权限
      break;
    case 403:
      localStorage.removeItem('token');
      break;
    case 404:
      break;
  }
  return response;
}, error => {
  let { response } = error;
  if (response) {
    // => 服务器返回结果了
    switch (Number(response.code)) {
      case 401: // 权限
        break;
      case 403:
        localStorage.removeItem('token');
        break;
      case 404:
        break;

    }
  } else {
    // => 服务器没返回结果
    if (!window.navigator.onLine) {
      // 断网处理: 可以跳转到断网页面
      return;
    }
    return Promise.reject(error);
  }
});

export default axiosInstance;